package com.fast.common.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fast.common.exception.FastException;

public class HttpTransport {
	/**
	 * http通讯错误
	 */
	public static final String HTTP_CONNECT_ERROR = "HTTP001";

	private static Logger logger = LoggerFactory.getLogger(HttpTransport.class);

	public static CloseableHttpClient createClient(RequestConfig config) throws FastException {
		SSLContext sslContext = null;
		try {
			sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				// 信任所有
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();
		} catch (KeyManagementException e) {
		} catch (NoSuchAlgorithmException e) {
		} catch (KeyStoreException e) {
		}
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
		return HttpClients.custom().setDefaultRequestConfig(config).setSSLSocketFactory(sslsf).build();
	}

	public static String httpGet(String url) throws FastException {
		return executor(url, null, MethodType.GET);
	}

	public static String httpPost(String url, String params) throws FastException {
		return executor(url, params, MethodType.POST);
	}

	private static String executor(String url, String params, MethodType type) throws FastException {
		logger.info("Http请求url地址==>{}", url);
		logger.info("请求参数：{}", params);
		Builder configBuild = RequestConfig.custom();
		configBuild.setSocketTimeout(60000);
		configBuild.setConnectionRequestTimeout(2000);
		configBuild.setConnectTimeout(2000);
		RequestConfig config = configBuild.build();
		HttpClient httpClient = null;
		if (url.startsWith("https://")) {
			httpClient = createClient(config);
		} else {
			httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
		}
		HttpUriRequest method = createRequest(url, params, type);
		HttpResponse result = null;
		try {
			result = httpClient.execute(method);
		} catch (ClientProtocolException e) {
			logger.error("", e);
			throw new FastException(HTTP_CONNECT_ERROR, e.getMessage());
		} catch (IOException e) {
			logger.error("", e);
			throw new FastException(HTTP_CONNECT_ERROR, e.getMessage());
		}
		if (result == null) {
			logger.error("发送http请求错误==");
			throw new FastException(HTTP_CONNECT_ERROR, "请求对象为空");
		}
		logger.info("Http响应信息：{}", result.getStatusLine());
		if (result.getStatusLine().getStatusCode() == 200) {
			try {
				/** 读取服务器返回过来的json字符串数据 **/
				String resultJson = EntityUtils.toString(result.getEntity(), "UTF-8");
				return resultJson;
			} catch (Exception e) {
				logger.error("", e);
				throw new FastException(HTTP_CONNECT_ERROR, e.getMessage());
			}
		} else {
			throw new FastException(HTTP_CONNECT_ERROR, result.getStatusLine().getReasonPhrase());
		}
	}

	private static HttpUriRequest createRequest(String url, String params, MethodType type) {
		if (MethodType.POST.equals(type)) {
			return createPostRequest(url, params);
		} else {
			return createGetRequest(url);
		}

	}

	private static HttpUriRequest createGetRequest(String url) {
		HttpGet method = new HttpGet(StringUtils.trimToEmpty(url));
		return method;
	}

	private static HttpUriRequest createPostRequest(String url, String params) {
		logger.info("Http请求参数==>{}", params);
		HttpPost method = new HttpPost(url);
		try {
			StringEntity entity = new StringEntity(params, "UTF-8");
			entity.setContentEncoding("UTF-8");
			entity.setContentType("application/xml");
			method.setEntity(entity);
		} catch (UnsupportedEncodingException e) {
			logger.error("", e);
		}
		return method;
	}
}
